from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q

from app.controllers.goods.category import category_controller
from app.controllers.goods.goods import goods_controller
from app.controllers.goods.sku import sku_controller
from app.models import GoodsSku
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.goods import *
from app.utils.upload import upload_image,upload_file
from app.models.goods import GoodsAttribute,GoodsCategory
from typing import Union
from app.settings import settings

all_goods_router = APIRouter()
model_name = "商品"


@all_goods_router.get("/list", summary=f"查看{model_name}列表")
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description=f"{model_name}名称"),
        state: Union[int, str] = Query(0, description="上架状态"),
        category_id: int = Query(None, description="类目"),
):
    q = Q()
    if name:
        q &= Q(name__contains=name)
    if state:
        q &= Q(state=int(state) - 1)
    if category_id:
        cate_ids = await category_controller.get_tree_ids(category_id)
        q &= Q(category_id__in=cate_ids)
    total, data = await goods_controller.do_list(page=page, page_size=page_size, search=q)

    category_objs = await goods_controller.categorys()
    for item in data:
        if item["category_id"]:
            item["lm"] = category_objs[item["category_id"]]
        goods_q = Q(goods_id=item['id'])
        goods_total, goods_data = await sku_controller.do_list(page=1, page_size=100, search=goods_q)
        item['sku'] = goods_data

        if item["sku"]:
            sku = item["sku"]
            kc,min_p,max_p = await goods_controller.sku_format(sku=sku)
            item["price"] = f"￥{min_p}~{max_p}"
            item["kc"] = kc
        item["sale_num"] = await goods_controller.sale_num(goods_id=item['id'])


    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@all_goods_router.get("/get", summary=f"查看{model_name}")
async def do_get(
        data_id: int = Query(..., description="ID"),
):
    data = await goods_controller.do_detail(data_id=data_id)
    return Success(data=data)

@all_goods_router.post("/create", summary=f"创建{model_name}")
async def do_create(
        category_in: GoodsCreate,
):
    ret = await goods_controller.do_create(obj_in=category_in)
    return ret

@all_goods_router.post("/update", summary=f"更新{model_name}")
async def do_update(
        category_in: GoodsUpdate,
):
    ret = await goods_controller.do_update(obj_in=category_in)
    return ret

@all_goods_router.delete("/delete", summary=f"删除{model_name}")
async def do_delete(
        data_id: int = Query(..., description="ID"),
):
    await goods_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

@all_goods_router.post("/file", summary="上传图片")
async def do_file(file: UploadFile):
    url = await upload_image(file,"goods/goods")
    if not url:
        return Fail(code=400, msg="图片格式错误")
    data = {"url": url}
    return Success(data=data)

@all_goods_router.get("/get_attr", summary="获取选择类目的属性列表和规格列表")
async def do_get_attr(
        data_id: int = Query(..., description="ID"),
):
    data = await GoodsCategory.filter(id=data_id).first().values("attribute_ms_id","attribute_gg_id")
    attribute_ms_id = data['attribute_ms_id']
    attribute_gg_id = data['attribute_gg_id']
    ms_data = []
    gg_data = []
    if attribute_ms_id:
        ms_data = await GoodsAttribute.filter(id__in=attribute_ms_id).values("tags")
    if attribute_gg_id:
        gg_data = await GoodsAttribute.filter(id__in=attribute_gg_id).values("tags")
    ret_data = dict()
    ret_data["ms_data"] = ms_data
    ret_data["gg_data"] = gg_data
    return Success(data=ret_data)

@all_goods_router.get("/all", summary="获取所有商品ID,名称和封面")
async def do_all():
    total, data = await goods_controller.do_list(page=1, page_size=100)
    ret_data = []
    for item in data:
        item["price"] = f"￥{0}~{0}"
        item["kc"] = 0
        if item["sku"]:
            sku = item["sku"]
            kc,min_p,max_p = await goods_controller.sku_format(sku=sku)
            item["price"] = f"￥{min_p}~{max_p}"
            item["kc"] = kc
        ret_item = {
            "value":item["id"],
            "label": item["name"],
            "cover": item["cover"],
            "price": item["price"],
        }
        ret_data.append(ret_item)
    return SuccessExtra(data=ret_data, total=total)

@all_goods_router.get("/type", summary="获取商品类型")
async def list_level():
    level_objs = settings.GOODS_TYPE
    data = []
    key = 0
    for level in level_objs:
        if level:
            data.append({"id":key,"name":level})
        key += 1
    return Success(data=data)

@all_goods_router.get("/type_array", summary="获取商品类型[数组形式]")
async def list_level2():
    level_objs = settings.GOODS_TYPE
    return Success(data=level_objs)

@all_goods_router.get("/goods_sku", summary="通过商品id获取商品sku")
async def do_sku_list(
        goods_id: int = Query(0, description="商品id"),
):
    data = await GoodsSku.filter(goods_id=goods_id).values("id","sku_name")
    ret_data = []
    for item in data:

        ret_item = {
            "value": item["id"],
            "label": item["sku_name"],
        }
        ret_data.append(ret_item)
    return SuccessExtra(data=ret_data)
